import { Component, OnInit,Inject } from '@angular/core';
import { UserService } from "../../user/user.service";
import { Router } from "@angular/router";
import {FormBuilder,FormGroup,FormControl,Validators} from '@angular/forms';
import { Observable } from 'rxjs/Observable';
@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.css']
})
export class LoginComponent implements OnInit {
  validateForm:FormGroup;
  alerts: any = [
  ]
  constructor(public userService: UserService, public router: Router,private fb: FormBuilder) { 
    if(this.userService.isLogin){
      this.router.navigate(['music']);
    }
    this.validateForm = this.fb.group({
      userName: [ '', [ Validators.required ], [ this.userNameAsyncValidator ] ],
      passWord: [ '', [ Validators.required ] ]
    });
  }

  ngOnInit() {
    
  }

  success() {
    this.router.navigateByUrl('user');
  }
  login(cred) {
    this.userService.login(cred).subscribe(data => {
      if (data.json()[0].status == true) {
        this.userService.setIsLogin('true');
        this.userService.setData(data.json());
        this.success();
      } else {
        this.alerts.push({
          type: 'danger',
          msg: `<strong>Warning!</strong> 登录失败！用户名或密码错误！`,
          timeout: 5000
        });
        this.userService.setIsLogin('false');
      }
    });
  }


  getFormControl(name) {
    return this.validateForm.controls[ name ];
  }

  userNameAsyncValidator = (control: FormControl): any => {
    return Observable.create(function (observer) {
      setTimeout(() => {
        if (control.value === '匿名'||control.value === 'admin'||new RegExp("^[ ]+$").test(control.value)) {
          observer.next({ error: true, duplicated: true });
        } else {
          observer.next(null);
        }
        observer.complete();
      }, 500);
    });
  };

}
